package com.example;

import java.io.*;
import java.net.*;

public class NetworkManager{
    private ServerSocket serverSocket;
    private Socket socket;
    private DataInputStream input;
    private DataOutputStream output;
    private boolean flag = true;    // 标记是否为己方回合
    private ChessController chessController;


    public NetworkManager(ChessController chessController) {
        this.chessController = chessController;
    }

    // 作为主机启动服务器
    public void startServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    // 等待客户端连接
    public Socket waitForClient() throws IOException {
        socket = serverSocket.accept();
        setupStreams();
        new Thread(this::listenForMessages).start();
        return socket;
    }

    // 作为客户端连接服务器
    public void connectToServer(String host, int port) throws IOException {
        socket = new Socket(host, port);
        setupStreams();
        new Thread(this::listenForMessages).start();
    }

    private void setupStreams() throws IOException {
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }

    // 监听来自对方的消息
    private void listenForMessages() {
        try {
            while (true) {
                int x = input.readInt();
                int y = input.readInt();
                chessController.moveChess(x, y);
                flag = true;        // 对方落子，轮换己方回合
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 发送移动信息给对方
    public void sendMove(int x, int y) throws IOException {
        output.writeInt(x);
        output.writeInt(y);
        output.flush();
        flag = false;               // 己方落子，切换为对方回合
    }

    public void close() {
        try {
            if (socket != null) socket.close();
            if (input != null) input.close();
            if (output != null) output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean isMyTurn() {
        return flag;
    }
}